package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.giftedcat.easylib.selector.MultiImageSelector;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.adapter.NineGridAdapter;
import com.zmx.patientend.listener.OnAddPicturesListener;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.pojo.Doctor;
import com.zmx.patientend.pojo.OrderDetails;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class GraphicVisitsActivity extends BaseActivity implements View.OnClickListener {

    private Button button1, button2, button3, button4, next;
    private EditText editText;
    private RadioButton radio_prescription,radio_video;
    private CardView gv;

    private RecyclerView rvImages;
    NineGridAdapter adapter;
    private int maxNum = 9;
    Unbinder unbinder;
    List<String> mSelect;
    List<String> select;//图片路径
    private static final int REQUEST_IMAGE = 2;

    private CircleImageView head;
    private TextView name,describe;

    private OrderDetails od;
    private Doctor doctor;
    private String asktype;

    private int is_call=0;//是否多方通话，默认为单方，1为多方

    private String team_id;//专家团的id

    @Override
    protected int getLayoutId() {
        return R.layout.activity_graphic_visits;
    }

    @Override
    protected void initViews() {

        setToolbar(R.id.tool_bar);
        od = new OrderDetails();
        doctor = (Doctor) this.getIntent().getSerializableExtra("doctor");
        asktype = this.getIntent().getStringExtra("asktype");
        team_id = this.getIntent().getStringExtra("team_id");
        Log.e("专家团尽力啊","进来聊聊1111team_id "+team_id);
        od.setDoctor(doctor);
        od.setAsktype(asktype);
        od.setKid(this.getIntent().getStringExtra("class_id"));
        button1 = findViewById(R.id.button1);
        button1.setOnClickListener(this);
        button2 = findViewById(R.id.button2);
        button2.setOnClickListener(this);
        button3 = findViewById(R.id.button3);
        button3.setOnClickListener(this);
        button4 = findViewById(R.id.button4);
        button4.setOnClickListener(this);
        next = findViewById(R.id.next);
        next.setOnClickListener(this);
        editText = findViewById(R.id.editText);
        name = findViewById(R.id.name);
        name.setText(doctor.getName());
        describe = findViewById(R.id.describe);
        describe.setText(doctor.getTitle_name());
        head = findViewById(R.id.head);
        Glide.with(this).load(doctor.getAvatar()).into(head);

        gv = findViewById(R.id.cv_item);

        if (team_id == null){

            gv.setVisibility(View.VISIBLE);

        }else{
            gv.setVisibility(View.GONE);

        }

        mSelect = new ArrayList<>();
        rvImages = findViewById(R.id.rv_images);
        rvImages.setLayoutManager(new GridLayoutManager(this, 3));
        adapter = new NineGridAdapter(this, mSelect, rvImages);
        adapter.setMaxSize(maxNum);
        rvImages.setAdapter(adapter);
        adapter.setOnAddPicturesListener(new OnAddPicturesListener() {
            @Override
            public void onAdd() {
                pickImage();
            }
        });

        radio_video = findViewById(R.id.radio_video);
        radio_prescription = findViewById(R.id.radio_prescription);

        toolbar.setTitle("在线问诊");

    }

    /**
     * 选择添加图片
     */
    private void pickImage() {

        MultiImageSelector selector = MultiImageSelector.create(mActivity);
        selector.showCamera(true);
        selector.count(maxNum);
        selector.multi();
        selector.origin(mSelect);
        selector.start(mActivity, REQUEST_IMAGE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case 2:
                if (resultCode == RESULT_OK) {

                    select = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);

                    mSelect.clear();
                    for (String s : select) {

                        if (s != "") {
                            Log.e("路径", "路径：" + s);
                            mSelect.add(s);
                        }
                    }

                    handler.sendEmptyMessage(1);

                    adapter.notifyDataSetChanged();
                }
                break;
        }

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        if (unbinder != null) {
            unbinder.unbind();
        }

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 1:
                    upload(mSelect);
                    break;

            }

        }
    };

    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()) {

            case R.id.button1:
                //判断是否已经有内容了
                if (editText.getText().toString().equals("")) {

                    editText.setText("症状描述：");

                } else {

                    editText.setText(editText.getText() + "\n" + "症状描述：");

                }
                break;

            case R.id.button2:

                //判断是否已经有内容了
                if (editText.getText().toString().equals("")) {

                    editText.setText("患者时长：");

                } else {

                    editText.setText(editText.getText()+ "\n" + "患者时长：");

                }
                break;

            case R.id.button3:
                if (editText.getText().toString().equals("")) {

                    editText.setText("医院检查：");

                } else {

                    editText.setText(editText.getText()+ "\n" + "医院检查：");

                }
                break;
            case R.id.button4:
                if (editText.getText().toString().equals("")) {

                    editText.setText("用药情况：");

                } else {

                    editText.setText(editText.getText()+ "\n" + "用药情况：");

                }
                break;

            case R.id.next:

                //判断描述是否为空
                if(AllUtil.isNotNull(editText.getText().toString())){

                    if (radio_video.isChecked()){
                        is_call = 1;
                    }

                    od.setContent(editText.getText().toString());
                    od.setImage_url(mSelect);
                    od.setIs_call(is_call);
                    Intent intent = new Intent(mActivity,AllPatientActivity.class);
                    intent.putExtra("od",od);
                    intent.putExtra("team_id",team_id);
                    startActivity(intent);

                }else{

                    Toast("请详细描述你的病情");

                }

                break;

            default:
                break;
        }

    }



    private void upload(List<String> url) {// selImageList 包含图片路径的list


        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); //表单上传文件


        for (String s:url){

            File file = new File(s); //根据路径创建file对象
            builder.addFormDataPart("image[]", //
                    file.getName(),
                    RequestBody.create(MediaType.parse("image/jpeg"), file)
            );
        }

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url("http://zmx.123xk.cn/addImg")
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure: ", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {

                    JSONObject object = new JSONObject(response.body().string());

                    Log.e("上传后返回的数据","上传后返回的数据"+object.toString());

                    if (object.getString("code").equals("1")) {

                    } else {
                        Toast(object.getString("msg"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }


}
